from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from config import Config

class BrowserDriver:
    #浏览器驱动管理类
    
    def __init__(self):
        self.chrome_options = self._setup_chrome_options()
    
    def _setup_chrome_options(self):
        #设置Chrome选项
        options = Options()
        for arg, value in Config.CHROME_OPTIONS.items():
            if value:
                options.add_argument(f"{arg}={value}")
            else:
                options.add_argument(arg)
        
        options.add_experimental_option("excludeSwitches", ["enable-automation"])
        options.add_experimental_option('useAutomationExtension', False)
        return options
    
    def init_driver(self):
        #初始化浏览器驱动
        try:
            driver = webdriver.Chrome(options=self.chrome_options)
            driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
            driver.set_page_load_timeout(30)
            driver.set_script_timeout(30)
            return driver
        except Exception as e:
            print(f"初始化浏览器失败: {e}")
            return None